//
//  ContentView.swift
//  TinyTankDemo_AR
//
//  Created by He Huang on 2023/1/15.
//

import RealityKit
import SwiftUI

var tankAnchor1: TinyToyTank._TinyToyTank?

struct ContentView1: View {
  @State var isPlaying = true
  
  var body: some View {
    
    ZStack {
      ARViewContainer(isPlaying: $isPlaying).edgesIgnoringSafeArea(.all)//占满全屏、
        
      //Buttons
      VStack{
        Spacer()
        
        HStack{
          Spacer()
          
          makeButtonsView()
        }
      }
    } // End ZStack
  } // End body
  
  func makeButtonsView() -> some View {
    VStack {
      HStack {
        // TurretLeft
        
        Button(action:{
          if isPlaying {
            return
          }
          else {
            isPlaying = true
            tankAnchor!.notifications.turretLeft.post()
          }
        }, label: {
          Image("CannonFire")
            .resizable()
            .frame(width: 80, height:80)
        })
        
        // TurrentRight
      }
      
      HStack {
        // Tank Left
        // Tank Forward
        // Tank Right
      }
      
    }
  }
}

                           
struct ContentView1_Previews: PreviewProvider {
   static var previews: some View {
       ContentView1()
   }
}
                           
//利用UIKit相关组件，做一个显示AR模型的SwiftUI工具
struct ARViewContainer1: UIViewRepresentable{
    @Binding var isPlaying: Bool
   func makeUIView(context: Context) -> some ARView {
       
       let arView = ARView(frame: .zero)
       
       //加载模型
       tankAnchor = try! TinyToyTank.load_TinyToyTank()
       tankAnchor?.cannon?.setParent(tankAnchor!.tank, preservingWorldTransform: true)
       tankAnchor?.actions.actionComplete.onAction = { _ in
           self.isPlaying = false
       }
       arView.scene.anchors.append(tankAnchor!)
       
       return arView
       
   }
   
   func updateUIView(_ uiView: UIViewType, context: Context) {
       
   }
}
